package com.dxl.controller;

import com.dxl.utils.QrCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * @author dxl
 * @date 2020/12/22 15:15
 */
@Api(tags = "二维码模块")
@RestController
@RequestMapping("/qrcode")
public class QrCodeController {
    /**
     * 生成 普通二维码
     */
     @ApiOperation("生成普通二维码")
     @GetMapping(value = "/getCommonQRCode")
    public void getCommonQRCode(HttpServletResponse response, String url) throws Exception {
        ServletOutputStream stream = null;
        try {
            stream = response.getOutputStream();
            //使用工具类生成二维码
            QrCodeUtil.encode(url,"",stream,false);
        } finally {
            if (stream != null) {
                stream.flush();
                stream.close();
            }
        }
    }

    /**
     * 把二维码保存成文件
     * @return
     */
    @GetMapping(value = "/qrsave")
    @ApiOperation("把二维码保存成文件")
    public String qrsave() {
        String requestUrl = "http://www.baidu.com";
        try {
//            QrCodeUtil.save(requestUrl, "/src/main/resources/static/favicon.ico", "/data/springboot2/qrcode2.jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "文件已保存";
    }
    /**
     * 生成 带有logo二维码
     */
    @ApiOperation("生成带有logo二维码")
    @GetMapping(value = "/getQRCodeWithLogo")
    public void getQRCodeWithLogo(HttpServletResponse response, String url) throws Exception {
        ServletOutputStream stream = null;
        try {
            stream = response.getOutputStream();
            // logo 地址
            String logoPath = Thread.currentThread().getContextClassLoader().getResource("").getPath()
                    + "templates" + File.separator + "advator.jpg";
            // String logoPath = "springboot-demo-list/qr-code/src/main/resources/templates/advator.jpg";
            //使用工具类生成二维码
            QrCodeUtil.encode(url, logoPath, stream, true);
        } finally {
            if (stream != null) {
                stream.flush();
                stream.close();
            }
        }
    }
    /**
     * 解析二维码内容
     */
    @ApiOperation("解析二维码内容")
    @GetMapping(value = "/decodeQrcode")
    public String decodeQrcode() throws Exception {
        String url = "";
        try {
            //https://img2020.cnblogs.com/blog/1938691/202008/1938691-20200806134311118-669906850.png
            url = QrCodeUtil.decode(Thread.currentThread().getContextClassLoader().getResource("").getPath()+"static/qrcode.jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "解析到的url:"+url;
    }
}
